package com.zyy.sqlSession;

import com.zyy.pojo.Configuration;
import com.zyy.pojo.MappedStatement;
import com.zyy.pojo.SqlCommandType;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author zyy
 * @date 2020/11/9 11:44 上午
 * @description
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(MappedStatement mappedStatement, Object... params) throws Exception {
        //将要去完成对SimpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(MappedStatement mappedStatement, Object... params) throws Exception {
        List<Object> objects = selectList(mappedStatement, params);
        if(objects.size() == 1){
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或返回结果过多");
        }
    }

    @Override
    public Integer update(MappedStatement mappedStatement, Object... param) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Integer row = simpleExecutor.update(configuration, mappedStatement, param);
        return row;
    }

    /**
     * 为Dao接口生成代理对象
     * @param mapperClass
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //代理对象中任意方法都会执行invoke方法
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层还是调用JDBC代码 根据情况不同 来调用selectList或者selectOne
                //准备参数1：statementid:sql语句的唯一标识：接口的全限定名.方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();

                String statementId = className + "."+ methodName;

                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
                Integer rows;
                //准备参数2： params args
                switch (sqlCommandType){
                    case INSERT:
                    case UPDATE:
                    case DELETE:
                        rows = update(mappedStatement, args);
                        return rows;
                    case SELECT:
                        //获取背调用方法的返回类型
                        Type genericReturnType = method.getGenericReturnType();
                        if(genericReturnType instanceof ParameterizedType){
                            List<Object> objects = selectList(mappedStatement, args);
                            return objects;
                        }
                        return selectOne(mappedStatement,args);
                    default:
                        throw new Exception("sqlCommandType error");
                }
            }
        });
        return (T) proxyInstance;
    }
}
